package com.example.mobile2030606148tdh0618;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
 private RecyclerView rvMainUsers;
 private Button btnMainInsert;
 private List<Users> list=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
       list=new MyDataAdapter().QueryAll(this);
        rvMainUsers.setAdapter(new UsersRViewAdapter(list));
        btnMainInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View view= LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_insert,null);
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("添加数据")
                        .setView(view)
                        .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                              String name=((EditText)view.findViewById(R.id.edtTxtDialogName))
                                .getText().toString().trim();
                              int age =Integer.valueOf(((EditText)view.findViewById(R.id.edtTxtDialogAge))
                                      .getText().toString().trim());
                              float score =Float.valueOf(((EditText)view.findViewById(R.id.edtTxtDialogScore)).getText().toString().trim());
                              new MyDataAdapter().insert(MainActivity.this,new Users(name,age,score));
                              list.clear();
                              list.addAll(new MyDataAdapter().QueryAll(MainActivity.this));
                              rvMainUsers.getAdapter().notifyDataSetChanged();
                            }
                        }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create().show();
            }
        });
    }
    private void initView(){
        rvMainUsers=(RecyclerView)findViewById(R.id.rvMainUsers);
        rvMainUsers.setLayoutManager(new LinearLayoutManager(this));
        btnMainInsert=(Button)findViewById(R.id.btnMainInsert);
    }

}